<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="出入库时间" prop="busiDate">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" clearable>
          <el-option
            v-for="dict in dict.type.bus_stock_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="单据状态" prop="status">
        <el-select v-model="queryParams.status" clearable>
          <el-option
            v-for="dict in dict.type.bus_bill_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="仓库" prop="storeId">
        <el-select v-model="queryParams.storeId" clearable>
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleImportStore"
          >入库</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleOutputStore"
          >出库</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="billList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据" align="center" prop="id" />
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope"
          ><dict-tag
            :options="dict.type.bus_stock_status"
            :value="scope.row.type"
          ></dict-tag
        ></template>
      </el-table-column>

      <el-table-column label="仓库" align="center" prop="storeName" />
      <el-table-column label="总数量" align="center" prop="totalCount" />
      <el-table-column label="总金额" align="center" prop="totalPrice" />
      <el-table-column label="操作人" align="center" prop="operator" />
      <el-table-column
        label="出入库时间"
        align="center"
        prop="busiDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.busiDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作时间"
        align="center"
        prop="operateDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operateDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope"
          ><dict-tag
            :options="dict.type.bus_bill_status"
            :value="scope.row.status"
          ></dict-tag
        ></template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status == 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handelCancelBill(scope.row)"
            >作废</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="checkSelectList(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 入库单据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="仓库" prop="storeId">
          <el-select v-model="form.storeId" clearable :disabled="isCheck">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出入库时间" prop="busiDate" :disabled="isCheck">
          <el-date-picker
            clearable
            v-model="form.busiDate"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择出入库时间"
            :disabled="isCheck"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            :disabled="isCheck"
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-button v-if="!isCheck" type="primary" @click="handelBillVisible"
          >添加明细</el-button
        >
        <!-- 明细列表 -->
        <el-table v-if="!isCheck" :data="billItemList">
          <el-table-column label="物品id" align="center" prop="goodsId" />
          <el-table-column label="物品名" align="center" prop="goodsName" />
          <el-table-column label="价格" align="center" prop="price">
            <template slot-scope="scope">
              <el-input-number
                :disabled="isCheck"
                size="small"
                v-model="scope.row.price"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center" prop="amounts">
            <template slot-scope="scope">
              <el-input-number
                :disabled="isCheck"
                size="small"
                v-model="scope.row.amounts"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="小计" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.amounts * scope.row.price }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" v-if="!isCheck">
            <template slot-scope="scope">
              <el-button @click="deleteBillItem(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <el-table v-if="isCheck" :data="billItemList2">
        <el-table-column label="物品id" align="center" prop="goodsId" />
        <el-table-column label="物品名" align="center" prop="goodsName" />
        <el-table-column label="价格" align="center" prop="price" />
        <el-table-column label="数量" align="center" prop="amounts" />
        <el-table-column label="小计" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.amounts * scope.row.price }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="!isCheck" @click="comfirmImport"
          >确认</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <!-- 商品选择对话框 -->
    <el-dialog
      title="请选择需要添加的商品"
      :visible.sync="selectVisible"
      width="900px"
      append-to-body
    >
      <!-- 商品列表搜索框 -->
      <el-form
        :model="queryProductParams"
        ref="queryProductForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="80px"
      >
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="queryProductParams.keywords" clearable> </el-input>
        </el-form-item>
        <el-form-item label="分类id" prop="categoryId">
          <el-select v-model="queryProductParams.categoryId" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleProductQuery"
            >搜索</el-button
          >
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="resetProductQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <!-- 商品选择列表 -->
      <el-table :data="productSelectList">
        <el-table-column label="物品id" align="center" prop="id" />
        <el-table-column label="图片" align="center" prop="goodsCover">
          <template slot-scope="scope">
            <img
              :src="scope.row.goodsCover"
              alt=""
              width="50px"
              height="50px"
            />
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" prop="goodsName" />
        <el-table-column label="品牌" align="center" prop="brand" />
        <el-table-column label="分类" align="center" prop="categoryName" />
        <el-table-column label="库存" align="center" prop="amounts" />

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              :disabled="
                billItemList.map((item) => item.goodsId).includes(scope.row.id)
              "
              @click="handelSelectProduct(scope.row)"
              >选择此物品</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="selectTotal > 0"
        :total="selectTotal"
        :page.sync="queryProductParams.pageNum"
        :limit.sync="queryProductParams.pageSize"
        @pagination="getProductList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectCancel">关闭弹框</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBill,
  billInfo,
  getBill,
  delBill,
  addBill,
  updateBill,
  cancelBill,
} from "@/api/business/stock";
import { listallStore, SelectStoreItems } from "@/api/business/store";
import { CategorySelect } from "@/api/business/category";

export default {
  name: "Bill",
  dicts: ["bus_stock_status", "bus_bill_status"],
  watch: {
    "form.storeId": {
      handler: function () {
        this.billItemList = [];
      },
      immediate: true,
    },
  },
  data() {
    return {
      // 当前storeId
      nowStoreId: null,
      // 是查看状态
      isCheck: false,
      // 出入库表示
      stockFlag: 1,
      // 商品列表对话框
      selectVisible: false,
      // 商品列表
      productSelectList: [
        {
          id: 1,
          goodsName: "苹果",
          goodsCover: "",
          categoryId: 12,
          brand: "大品牌",
          amounts: 100,
        },
      ],
      // 明细列表数据
      billItemList: [
        {
          goodsId: 1,
          goodsName: "苹果",
          price: 100,
          amounts: 2,
        },
        {
          goodsId: 2,
          goodsName: "梨",
          price: 200,
          amounts: 2,
        },
        {
          goodsId: 3,
          goodsName: "西瓜",
          price: 300,
          amounts: 2,
        },
      ],
      // 仓库数据
      options: [
        { value: 1, label: "仓库1" },
        { value: 2, label: "仓库2" },
        { value: 3, label: "仓库3" },
      ],
      // 分类数据
      categoryOptions: [
        { value: 1, label: "分类1" },
        { value: 2, label: "分类2" },
        { value: 3, label: "分类3" },
      ],
      // 操作时间访问
      dateRange: [],
      billItemList2: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 总条数
      selectTotal: 0,
      // 出入库单据表格数据
      billList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        storeId: null,
        busiDate: null, //入库时间
        status: null,
        operateDate: null,
        operatorId: null,
      },
      // 查询商品列表参数
      queryProductParams: {
        pageNum: 1,
        pageSize: 10,
        keywords: "",
        categoryId: null, //分类
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        storeId: [{ required: true, message: "请选择仓库", trigger: "blur" }],
        busiDate: [
          { required: true, message: "出入库时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getStoreList();
    this.getCategorySelect();
  },
  methods: {
    /* 获取分类下来选框 */
    getCategorySelect() {
      CategorySelect().then((res) => {
        this.categoryOptions = res.data.map((item) => {
          return {
            value: item.id,
            label: item.categoryName,
          };
        });
      });
    },
    /* 作废bill */
    handelCancelBill(row) {
      cancelBill(row.id).then((res) => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });
    },
    onStoreIdChange(value) {
      console.log("出发了");
      console.log(value);
    },
    /** 获取storeLis */
    getStoreList() {
      listallStore().then((res) => {
        console.log(res);
        this.options = res.data.map((item) => {
          return { value: item.id, label: item.storeName };
        });
      });
    },
    getSelectStoreItems(storeId) {
      SelectStoreItems(this.queryProductParams, storeId).then((res) => {
        this.productSelectList = res.rows.map((item) => {
          return {
            id: item.id,
            goodsName: item.goodsName,
            goodsCover: item.goodsCover,
            categoryName: item.categoryName,
            brand: item.brand,
            amounts: item.amounts,
          };
        });
        this.selectVisible = true;
        this.selectTotal = res.total;
      });
    },
    /* 查看已选 */
    checkSelectList(row) {
      this.title = "查看";
      this.billItemList2 = [];
      this.getBillList(row);
    },
    // 获取
    getBillList(row) {
      billInfo(row.id).then((res) => {
        this.billItemList2 = res.data.stockBillItems;
        this.form = {
          busiDate: res.data.busiDate,
          remark: res.data.remark,
          storeId: row.storeId,
        };

        this.isCheck = true;
        this.open = true;
      });
    },
    /* 选择商品 */
    handelSelectProduct(row) {
      let product = {
        goodsId: row.id,
        goodsName: row.goodsName,
        price: 0,
        amounts: 0,
      };
      this.billItemList.push(product);
    },
    /* 打开明细选择表 */
    handelBillVisible() {
      this.nowStoreId = this.form.storeId;

      if (this.form.storeId == null) {
        this.$modal.msgError("请选择仓库");
        return;
      }
      this.getSelectStoreItems(this.form.storeId);
    },

    /* 删除明细列表id */
    deleteBillItem(row) {
      this.billItemList = this.billItemList.filter(
        (item) => item.goodsId != row.goodsId
      );
    },
    /* 确认入库 */
    comfirmImport() {
      let data = {
        ...this.form,
        type: this.stockFlag,
        stockBillItems: this.billItemList,
      };
      console.log(data);
      addBill(data).then((response) => {
        this.$modal.msgSuccess("新增成功");
        this.open = false;
        this.getList();
        this.billItemList = [];
      });
    },
    /** 查询出入库单据列表 */
    getList() {
      this.loading = true;
      listBill(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.billList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /* 获取产品选择的数据列表 */
    getProductList() {
      console.log(this.queryProductParams);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    selectCancel() {
      this.selectVisible = false;
      //   this.resetProduct();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        storeId: null,
        busiDate: null,
        status: 0,
        operateDate: null,
        operatorId: null,
        remark: null,
      };
      this.isCheck = false;
      this.resetForm("form");
    },
    // 产品列表重置
    resetProduct() {
      this.form = {
        keywords: "",
        categoryId: null, //分类
      };
      this.resetForm("queryProductForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 搜索产品列表按钮操作 */
    handleProductQuery() {
      this.queryProductParams.pageNum = 1;
      this.getSelectStoreItems(this.nowStoreId);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 重置产品列表按钮操作 */
    resetProductQuery() {
      this.resetForm("queryProductForm");
      this.handleProductQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 入库按钮操作 */
    handleImportStore() {
      this.stockFlag = 1;
      this.billItemList = [];
      this.reset();
      this.open = true;
      this.title = "添加入库单据";
    },

    /** 出库按钮操作 */
    handleOutputStore() {
      this.stockFlag = 0;
      this.billItemList = [];
      this.reset();
      this.open = true;
      this.title = "添加出库单据";
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBill(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBill(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
  },
};
</script>
